//
//  HZL_PlayerViewController.m
//  B_Project
//
//  Created by 刘峻豪 on 15/11/30.
//  Copyright © 2015年 HZL. All rights reserved.
//

#import "HZL_PlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

#define FRAME_WIDTH self.view.frame.size.height
#define FRAME_HEIGHT self.view.frame.size.width

@interface HZL_PlayerViewController ()
@property (nonatomic, retain) AVPlayer *player; // 播放器的状态类型
@property (nonatomic, retain) AVPlayerItem *playerItem; // 设置AV的详细类型
@property (nonatomic, retain) UIView *backView;
@property (nonatomic, assign) BOOL isPlay; // 播放状态
@property (nonatomic, retain) UILabel *leftTime;
@property (nonatomic, retain) UILabel *timeLabel; // 播放时间
@property (nonatomic, retain) UIButton *backBtn;
@property (nonatomic, retain) UIButton *playBtn;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) UIProgressView *progress;
@property (nonatomic, retain) UISlider *slider; // 声音
@property (nonatomic, retain) UIView *lightView; // 屏幕亮度
@property (nonatomic, retain) UIView *volumeView; // 声音
@property (nonatomic, assign) CGFloat systemVolume;
@property (nonatomic, strong) UISlider *volumeViewSlider;
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation HZL_PlayerViewController
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
// 屏幕支持那些方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    // 支持左右
    return UIInterfaceOrientationMaskLandscape;
}
//
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeRight;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [self.timer invalidate];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    
    // 网络
    NSURL *url = [NSURL URLWithString:self.playUrl];
    NSLog(@"~~~~~~```%@", self.playUrl);
    // 创建初始化
    self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
    // 需要在layer上进行操作
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = CGRectMake(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
    [self.view.layer addSublayer:playerLayer];
    
    // AVPlayer播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    // 给AVPlayer添加观察者(loadedTimeRange属性)
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    // 播放
    [self.player play];
    self.isPlay = YES;
    
    // 创建视图
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FRAME_WIDTH, FRAME_HEIGHT)];
    self.backView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.backView];
    
    // 屏幕亮度
    self.lightView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, FRAME_WIDTH / 2 - 50, FRAME_HEIGHT - 160)];
    [self.view addSubview:self.lightView];
    
    // 声音
    self.volumeView = [[UIView alloc] initWithFrame:CGRectMake(FRAME_WIDTH / 2 + 50, 60, FRAME_WIDTH / 2, FRAME_HEIGHT - 160)];
    [self.view addSubview:self.volumeView];
    
    
    // 添加手势
    [self creatGesture];
    // 创建播放时间label,button等控件
    [self creatControl];
    
    // 多线程5秒内完成
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.player play];
        // 2秒后消失
        [UIView animateWithDuration:2 animations:^{
            self.backView.alpha = 0;
        }];
    });
    
    // 加定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(stack) userInfo:nil repeats:YES];
    
    
    //获取系统音量
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    self.volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            self.volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    
}
#pragma mark - 观察者方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        // 获取缓冲范围的数组
        NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
        NSLog(@"%@", loadedTimeRanges);
        // 取数组中的元素 转化成CMTimerange类型
        CMTimeRange timeRange = [loadedTimeRanges.lastObject CMTimeRangeValue];
        // 开始的点
        CGFloat start = CMTimeGetSeconds(timeRange.start);
        // 经历的时间
        CGFloat duration = CMTimeGetSeconds(timeRange.duration);
        // 获取已经缓冲的长度
        NSTimeInterval totalTime = start + duration;
        // 获取视频的总长度
        CGFloat total = self.playerItem.duration.value / self.playerItem.duration.timescale;
        // 给缓存条赋值
        [self.progress setProgress:totalTime / total animated:YES];
    }
}
#pragma mark - 创建backView上的控制button
- (void)creatControl
{
    // 返回按钮
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.backBtn.backgroundColor = [UIColor blueColor];
    self.backBtn.frame = CGRectMake(20, 15, 25, 25);
    [self.backBtn setImage:[UIImage imageNamed:@"iconfont-xiangzuo"] forState:UIControlStateNormal];
    [self.backView addSubview:self.backBtn];
    [self.backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    // 题目
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 15, VIEW_WIDTH - 50, 25)];
//    self.titleLabel.backgroundColor = [UIColor blueColor];
    self.titleLabel.textColor = [UIColor grayColor];
    self.titleLabel.text = self.titlee;
    [self.backView addSubview:self.titleLabel];
    
    // 创建播放暂停按钮
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.playBtn.backgroundColor = [UIColor blueColor];
    self.playBtn.frame = CGRectMake(FRAME_WIDTH / 2 - 20, FRAME_HEIGHT / 2 - 20, 40, 40);
    [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    [self.backView addSubview:self.playBtn];
    [self.playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 时间
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(FRAME_WIDTH - 60, FRAME_HEIGHT - 41, 60, 30)];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.font = [UIFont systemFontOfSize:15];
    self.timeLabel.text = @"00.00";
    [self.backView addSubview:self.timeLabel];
    
    self.leftTime = [[UILabel alloc] initWithFrame:CGRectMake(20, FRAME_HEIGHT - 42, 60, 30)];
    self.leftTime.textColor = [UIColor whiteColor];
    self.leftTime.font = [UIFont systemFontOfSize:15];
    self.leftTime.text = @"00.00";
    [self.backView addSubview:self.leftTime];
    
    
    
    
    // 创建缓冲进度条progress
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(70, FRAME_HEIGHT-28, FRAME_WIDTH - 140, 15)];
    self.progress.progressTintColor = [UIColor grayColor];
    self.progress.trackTintColor = [UIColor whiteColor];
    [self.backView addSubview:self.progress];
    
    // 创建slider
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(68, FRAME_HEIGHT- 35, FRAME_WIDTH - 140, 15)];
    // 滑动后颜色
    self.slider.maximumTrackTintColor = [UIColor clearColor];
    self.slider.minimumTrackTintColor = [UIColor whiteColor];
    [self.backView addSubview:self.slider];
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
}


#pragma mark - 播放暂停的方法
- (void)playAction:(UIButton *)Btn
{
    Btn.selected = !Btn.selected;
    if (Btn.selected) {
        [self.playBtn setImage:[UIImage imageNamed:@"iconfont-yinlebofang"] forState:UIControlStateNormal];
        [self.player pause];
    } else {
        [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        [self.player play];
    }
}
#pragma mark - 进度条方法
- (void)sliderAction:(UISlider *)slider
{

    // 获取视频总时间
    CGFloat total = self.playerItem.duration.value / self.playerItem.duration.timescale;
    // 滑动之后当前的时间
    CGFloat currentTime = total * slider.value;
    // 必须转化成CMTime类型才能赋值
    CMTime time = CMTimeMake(currentTime, 1);
    [self.player pause];
    [self.player seekToTime:time completionHandler:^(BOOL finished) {
        // 滑动完成后播放视频
        [self.player play];
    }];
}
#pragma mark - 返回按钮方法
- (void)backAction
{
    self.player.rate = 0.0; // 播放器停止
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


#pragma mark - 视频播放结束-通知中心方法
- (void)moviePlayDidEnd
{
    self.player.rate = 0.0; // 播放器停止
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 定时器方法
- (void)stack
{
    if (self.playerItem.duration.timescale != 0) {
        
        
        _slider.maximumValue = 1;//总共时长
        _slider.value = CMTimeGetSeconds([_playerItem currentTime]) / (_playerItem.duration.value / _playerItem.duration.timescale);//当前进度
        // 计算当前视频的总秒数/60 = 分钟
        NSInteger minTotal = self.playerItem.duration.value / self.playerItem.duration.timescale / 60;
        // 总秒数
        NSInteger secTotal = self.playerItem.duration.value / self.playerItem.duration.timescale % 60;
        
        NSInteger min = (NSInteger)CMTimeGetSeconds([self.player currentTime]) / 60; // 当前分钟
        NSInteger sec = (NSInteger)CMTimeGetSeconds([self.player currentTime]) % 60; // 当前秒
        
        // 给label赋值
        self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",  minTotal, secTotal];
        
        self.leftTime.text = [NSString stringWithFormat:@"%02ld:%02ld", min, sec];
    }
}

#pragma mark - 创建轻拍手势 + 拖拽手势
- (void)creatGesture
{
    // 轻拍一次出现或者消失backView
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    // 轻拍两次暂停或者播放
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapAction:)];
    // 轻拍2次
    doubleTap.numberOfTapsRequired = 2;
    [self.view addGestureRecognizer:doubleTap];
    // 可以执行双击手势
    [tap requireGestureRecognizerToFail:doubleTap];
    
    
    // 拖拽控制屏幕亮度
    UIPanGestureRecognizer *lightPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(lightAction:)];
    [self.lightView addGestureRecognizer:lightPan];
    
    // 拖拽控制音量
    UIPanGestureRecognizer *volumePan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(volumeAction:)];
    [self.volumeView addGestureRecognizer:volumePan];
}

#pragma mark - 轻拍一次方法(暂停/播放)
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (self.backView.alpha == 1) {
        [UIView animateWithDuration:0.5 animations:^{
            self.backView.alpha = 0;
        }];
    } else if (self.backView.alpha == 0){
        [UIView animateWithDuration:0.5 animations:^{
            self.backView.alpha = 1;
        }];
    }
    if (self.backView.alpha == 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 暂停5秒后消失 前进后退暂停button
            [UIView animateWithDuration:0.5 animations:^{
                self.backView.alpha = 0;
            }];
        });
    }
}
#pragma mark - 轻拍两次方法
- (void)doubleTapAction:(UITapGestureRecognizer *)doubleTap
{
    // 判断如果正在播放->暂停 将状态设为NO
    if (self.isPlay == YES) {
        [self.player pause];
        self.isPlay = NO;
    } // 如果暂停状态->播放 状态设为YES
    else if (self.isPlay == NO) {
        [self.player play];
        self.isPlay = YES;
    }
}
#pragma mark - 控制亮度方法
- (void)lightAction:(UIPanGestureRecognizer *)lightPan
{
    CGPoint startPoint = [lightPan translationInView:self.lightView];
    NSLog(@"%.2f", startPoint.y);
    [UIScreen mainScreen].brightness = -startPoint.y * 0.005;
}

#pragma mark - 控制音量方法
- (void)volumeAction:(UIPanGestureRecognizer *)volumePan
{
    CGPoint p = [volumePan translationInView:self.volumeView];
    NSLog(@"%f", p.y);
    
    NSLog(@"%f", p.y);
    int index = (int)p.y;
    if (index > 0) {
        
        if(index % 10 == 0){//每10个像素声音减一格
            if(_systemVolume >= 0.05){
                _systemVolume = _systemVolume-0.05;
                NSLog(@"systemVolume                    %.2f", _systemVolume);
                [_volumeViewSlider setValue:_systemVolume animated:YES];
                [_volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
            }
        }
        
    }else if(index < 0)
    {
        if(index % 10 == 0){//每10个像素声音增加一格
            //NSLog(@"+x ==%d",index);
            NSLog(@"11111111111111                      %.2f",_systemVolume);
            if(_systemVolume >= 0 && _systemVolume < 1){
                _systemVolume = _systemVolume+0.05;
                [_volumeViewSlider setValue:_systemVolume animated:YES];
                [_volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
            }
        }
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
